<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class ChatController extends Controller
{
    // 闲言碎语列表
	public function chat_list()
	{
		$chats = DB::table('chat')->orderBy('chid','desc')->paginate(20);
		return view('admin/chat_list',['chats'=>$chats]); 
	}
	
	// 禁用列表
	public function chat_status(Request $request)
	{
		if($request->isMethod('post')){
			$chid = $request->input('chid');
			$is_show = $request->input('is_show');
			if(!preg_match('/^[1-9]\d*$/',$chid)) json_return(1000,'参数错误');
			if(!preg_match('/^[0-1]\d*$/',$is_show)) json_return(1000,'参数错误');
			# 修改状态
			$res = DB::table('chat')->where('chid',$chid)->update(['is_show'=>$is_show]);
			if($res){
				json_return(200,'操作成功');
			} else {
				json_return(200,'操作失败');
			}
		} else {
			json_return(1000,'非法操作');
		}
	}
	
	// 添加列表
	public function chat_add(Request $request)
	{
		if($request->isMethod('post')){
			$content = $request->input('content','','htmlspecialchars');
			if(empty($content)) return redirect('/prompt')->with(['message'=>'内容不能为空','url' =>'/admin/chat_add', 'jumpTime'=>3,'status'=>'error']);
			
			# 插入数据
			$res = DB::table('chat')->insert(['content'=>$content,'create_time'=>time()]);
			if($res){
				return redirect('admin/chat_list');
			} else {
				return redirect('/prompt')->with(['message'=>'添加失败，请联系客服','url' =>'/admin/chat_add', 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/chat_add');
	}
	
	// 修改列表
	public function chat_edit(Request $request,$chid)
	{
		if(!preg_match('/^[1-9]\d*$/',$chid)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/chat_list', 'jumpTime'=>3,'status'=>'error']);
		# 查询内容
		$chat = DB::table('chat')->where('chid',$chid)->select('content','chid')->first();
		if($request->isMethod('post')){
			$content = $request->input('content','','htmlspecialchars');
			if(empty($content)) return redirect('/prompt')->with(['message'=>'内容不能为空','url' =>'/admin/chat_add', 'jumpTime'=>3,'status'=>'error']);
			
			# 更新数据
			$res = DB::table('chat')->where('chid',$chid)->update(['content'=>$content]);
			if($res){
				return redirect('admin/chat_list');
			} else {
				return redirect('/prompt')->with(['message'=>'更新失败，请联系客服','url' =>'/admin/chat_edit/'.$chid, 'jumpTime'=>3,'status'=>'error']);
			}
		}
		return view('admin/chat_edit',['chat'=>$chat]);
	}
	
	// 删除列表
	public function chat_del(Request $request)
	{
		if($request->isMethod('post')){
			$chid = $request->input('chid');
			if(!preg_match('/^[1-9]\d*$/',$chid)) return redirect('/prompt')->with(['message'=>'参数错误','url' =>'/admin/chat_list', 'jumpTime'=>3,'status'=>'error']);
			
			# 删除数据
			$res = DB::table('chat')->where('chid',$chid)->delete();
			if($res){
				json_return(200,'删除成功');
			} else {
				json_return(1000,'删除失败');
			}
		}
	}
	
	
	
}
